995F - Cowmpany Cowmpensation - CodeForces Solution


combinatorics dp math trees *2700

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
#define ii pair<int,int>
#define f first
#define s second
#define pb push_back
#define int long long
#define endl '\n'
using namespace std;
const int MAXN = 1e18;
const int mod = 1e9 + 7;
int fact[3005];
int infact[3005];
int pre[3005];
int suf[3005];
int a[3005];
vector<int> w[3005];
int dp[3005][3005];
int n,d;
void DFS(int u)
{
	for(int i = 1;i <= n;i++)
	{
		dp[u][i] = 1;
	}
	for(int v : w[u])
	{
		DFS(v);
		for(int i = 1;i <= n;i++)
		{
			dp[u][i] = (dp[u][i] * dp[v][i]) % mod;
		}
	}
	for(int i = 1;i <= n;i++)
	{
		dp[u][i] = (dp[u][i] + dp[u][i - 1]) % mod;
	}
}
int binpow(int x,int y)
{
	int res = 1;
    while (y > 0) 
	{
        if (y % 2 == 1)
            res = (res * x) % mod;
        y = y >> 1;
        x = (x * x) % mod;
    }
    return res % mod;
}
void AcSolution()
{
	cin >> n >> d;
	dp[1][0] = 0;
	for(int i = 2;i <= n;i++)
	{
		int u;
		cin >> u;
		w[u].push_back(i);
	}
	n++;
	DFS(1);
	for(int i = 1;i <= min(n,d);i++)
	{
		a[i] = dp[1][i];
	}
	if(d <= n)
	{
		cout << a[d] << endl;
		return; 
	}
	pre[0] = 1;
	for(int i = 1;i <= n;i++)
	{
		pre[i] = (pre[i - 1] % mod * (d - i)) % mod;
	}
	suf[n + 1] = 1;
	for(int i = n;i >= 1;i--)
	{
		suf[i] = (suf[i + 1] % mod * (d - i)) % mod;
	} 
	fact[0] = 1;
	for(int i = 1;i <= n;i++)
	{
		fact[i] = ((fact[i - 1] % mod) * i) % mod;
	}
	infact[n] = binpow(fact[n], mod - 2);
    for (int i = n - 1; i >= 0; i--) 
	{
        infact[i] = infact[i + 1] * (i + 1) % mod;
    }
	int res = 0;
	for(int i = 1;i <= n;i++)
	{
		int x = a[i] * pre[i - 1] % mod * suf[i + 1] % mod * infact[n - i] % mod * infact[i - 1] % mod;
		if(i % 2 != n % 2)
		{
			x = -x;
		} 
		res = (res + x + mod) % mod;
	}
	cout << res << endl;
}
signed main()
{
//	freopen("BDIGIT.inp", "r",stdin);
//    freopen("BDIGIT.out", "w",stdout);
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int t = 1;
//	cin >> t;
	while(t--)
	{
	 	AcSolution();
	}
}



	  			 		  	 	    		 					    	


Comments

Submit
0 Comments
More Questions

1296A - Array with Odd Sum
1385A - Three Pairwise Maximums
911A - Nearest Minimums
102B - Sum of Digits
707A - Brain's Photos
1331B - Limericks
305B - Continued Fractions
1165B - Polycarp Training
1646C - Factorials and Powers of Two
596A - Wilbur and Swimming Pool
1462B - Last Year's Substring
1608B - Build the Permutation
1505A - Is it rated - 2
169A - Chores
765A - Neverending competitions
1303A - Erasing Zeroes
1005B - Delete from the Left
94A - Restoring Password
1529B - Sifid and Strange Subsequences
1455C - Ping-pong
1644C - Increase Subarray Sums
1433A - Boring Apartments
1428B - Belted Rooms
519B - A and B and Compilation Errors
1152B - Neko Performs Cat Furrier Transform
1411A - In-game Chat
119A - Epic Game
703A - Mishka and Game
1504C - Balance the Bits
988A - Diverse Team